#include "app_iwdg.h"

#define LOG_TAG              "wdt"
#include <drv_log.h>


rt_uint32_t restart_count = 0;
/*************************rt_thread***************************************/
struct rt_thread feed_iwdg_sta_thread;//喂狗
/*************************rt_stack****************************************/
ALIGN(RT_ALIGN_SIZE)
static rt_uint8_t rt_feed_iwdg_thread_stack[512];//线程栈 


#define IWDG_DEVICE_NAME    "wdt"    /* 看门狗设备名称 */

static rt_device_t wdg_dev;         /* 看门狗设备句柄 */


void feed_wdt_entry(void* parameter)
{
  while(1)
	{
		rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_KEEPALIVE, NULL);
		
		rt_thread_mdelay(1000);
	}
}
//static void idle_hook(void)
//{
//    /* 在空闲线程的回调函数里喂狗 */
//    rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_KEEPALIVE, NULL);
////    rt_kprintf("feed the dog!\n ");
//}
int app_int_wdt_thread(void)
{
		rt_err_t ret = RT_EOK;
    rt_uint32_t timeout = 2;    /* 溢出时间 */
		wdg_dev = rt_device_find(IWDG_DEVICE_NAME);
    if (!wdg_dev)
    {
        LOG_E("find %s failed!\n", IWDG_DEVICE_NAME);
    }
    /* 初始化设备 */
    ret = rt_device_init(wdg_dev);
    if (ret != RT_EOK)
    {
        LOG_E("initialize %s failed!\n", IWDG_DEVICE_NAME);
    }
    /* 设置看门狗溢出时间 */
    ret = rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_SET_TIMEOUT, &timeout);
    if (ret != RT_EOK)
    {
        LOG_E("set %s timeout failed!\n", IWDG_DEVICE_NAME);
    }
		  /* 启动看门狗 */
    ret = rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_START, RT_NULL);
    if (ret != RT_EOK)
    {
        LOG_E("start %s failed!\n", IWDG_DEVICE_NAME);
    }
    /* 设置空闲线程回调函数 */
    //rt_thread_idle_sethook(idle_hook);
		//rt_device_control(wdg_dev, RT_DEVICE_CTRL_WDT_START, NULL);
		// 创建静态线程 - 喂狗
    rt_thread_init(&feed_iwdg_sta_thread,              //线程控制块
                   "iwdg",                        		 //线程名字，在shell里面可以看到
                   feed_wdt_entry,           	 				 //线程入口函数
                   RT_NULL,                     		   //线程入口函数参数
                   &rt_feed_iwdg_thread_stack[0],      //线程栈起始地址
                   sizeof(rt_feed_iwdg_thread_stack),  //线程栈大小
                   iwdg_feed_pro,    								   //线程的优先级
                   20);                         		   //线程时间片
    rt_thread_startup(&feed_iwdg_sta_thread);          //启动线程 					 
		return RT_EOK;
}
INIT_APP_EXPORT(app_int_wdt_thread);
